#include <stdio.h>
#include <stdlib.h>
#define HEAPSIZE 10

void max_heapify(int* A, int i){
  int l, r, largest;
  l = 2 * i;
  r = 2 * i + 1;

  if( l <= HEAPSIZE && A[l] > A[i]){
    largest = l;
  } else{
    largest = i;
  }
  
  if( r <= HEAPSIZE && A[r] > A[largest]){
    largest = r;
  }

  if(largest != i){
    int temp = A[i];
    A[i] = A[largest];
    A[largest] = temp;
    max_heapify(A, largest);
  }
} /* está fêto */

int main(){
  int* A = (int*) malloc(HEAPSIZE * sizeof(int));
  int k;

  A -= 1;
  A[1] = 16;
  A[2] = 4;
  A[3] = 10;
  A[4] = 14;
  A[5] = 7;
  A[6] = 9;
  A[7] = 3;
  A[8] = 2;
  A[9] = 8;
  A[10] = 1;

  max_heapify(A, 2);

  for(k=1; k <= HEAPSIZE; k++){
    printf("%d\n", A[k]); 
  }

  A += 1;
  free(A);
}
